package com.ruicar.afs.cloud.afscase.processor.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.afscase.approvetask.entity.CaseApproveRecord;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkProcessScheduleInfoTemp;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.cargpsmanage.service.CarGpsApplyService;
import com.ruicar.afs.cloud.afscase.cargpsmanage.service.GpsManageService;
import com.ruicar.afs.cloud.afscase.common.utils.Const;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseContractInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseContractInfoService;
import com.ruicar.afs.cloud.afscase.processor.entity.WorkExceptionInfo;
import com.ruicar.afs.cloud.afscase.processor.enums.LoanSubmitEnum;
import com.ruicar.afs.cloud.afscase.processor.service.LoanGpsAuditWorkflowService;
import com.ruicar.afs.cloud.afscase.processor.service.WorkExceptionInfoService;
import com.ruicar.afs.cloud.afscase.processor.util.WorkflowTypeUtil;
import com.ruicar.afs.cloud.afscase.processor.vo.LoanWorkflowDataVO;
import com.ruicar.afs.cloud.afscase.processor.vo.NormalTaskSubmitVO;
import com.ruicar.afs.cloud.common.core.enums.AfsBaseEnum;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.SpringContextHolder;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.StartFlowRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.TaskSubmitRequest;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @author yk.Li
 * @Date 2020/7/17 GPS工作流
 * @description
 */
@Service
@Slf4j
@AllArgsConstructor
public class LoanGpsAuditWorkflowServiceImpl implements LoanGpsAuditWorkflowService {
    private WorkflowService workflowService;
    private CaseApproveRecordService caseApproveRecordService;
    private CarGpsApplyService carGpsApplyService;
    private CaseContractInfoService caseContractInfoService;

    @Transactional
    @Override
    public WorkFlowResponse start(LoanWorkflowDataVO loanWorkflowDataVO) {
        WorkProcessScheduleInfoTemp temp = loanWorkflowDataVO.getWorkProcessScheduleInfoTemp();
        if (null != temp) {
            StartFlowRequest request = new StartFlowRequest();
            request.setBizDataId(Convert.toStr(temp.getId()));
            request.setAfsFlowKey(temp.getAfsFlowKey());
            request.setFlowName(new StringBuffer(temp.getContractNo())
                    .append("-")
                    .append(WorkflowTypeUtil.getApproveTypeName(temp.getAfsFlowKey()))
                    .append("(")
                    .append(WorkflowTypeUtil.getType(temp.getAfsFlowKey()).getDesc())
                    .append(")").toString());
            WorkFlowResponse response = workflowService.startWorkFlow(request, new JSONObject());
            if (Const.WORKFLOW_RESPONSE_SUCCESS == response.getSuccess()) {
                saveStartRecord(temp);
            }
            return response;
        }
        return null;
    }

    /**
     * @param
     * @description 保存流程发起日志
     * @author yk.Li
     * @date 2020/7/17
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveStartRecord(WorkProcessScheduleInfoTemp infoTemp) {
        CaseApproveRecord record = new CaseApproveRecord();
        record.setDisposeNodeName("开始节点");
        record.setStageId(Convert.toStr(infoTemp.getId()));
        record.setContractNo(infoTemp.getContractNo());
        record.setApplyNo(infoTemp.getApplyNo());
        record.setApproveSuggestName("发起GPS审核流程");
        record.setApproveType(ApproveTypeEnum.PROCESS.getValue());
        record.setCurrentPosition(CurrentPositionEnum.GPS_AUDIT);
        record.setApproveStartTime(infoTemp.getStartTime());
        record.setApproveEndTime(infoTemp.getStartTime());
        record.setUseScene(UseSceneEnum.GENERAL_LOAN.getValue());
        caseApproveRecordService.save(record);

        //更新GPS申请表审核状态
        caseContractInfoService.updateWorkflowStatus(infoTemp.getContractNo(),GpsStatusEnum.FIRST_TRIAL);
        carGpsApplyService.updateApplyStatus(infoTemp.getContractNo(),GpsStatusEnum.FIRST_TRIAL,null);
    }

    @Transactional
    @Override
    public WorkFlowResponse submit(NormalTaskSubmitVO submitVO) {
        SpringContextHolder.getBean(LoanApproveWorkflowServiceImpl.class).isNull(submitVO);
        LoanSubmitEnum loanSubmitEnum = (LoanSubmitEnum) AfsEnumUtil.getEnum(submitVO.getRecord().getApproveSuggest(), LoanSubmitEnum.class);
        switch (loanSubmitEnum) {
            case SUBMIT:
                submitLoan(submitVO);
                break;
            case BACK_PARTNERS:
                submitBackToPartners(submitVO);
                break;
            case SECOND_ASSIGNMENT:
                secondAssignment(submitVO);
                break;
            default:
                log.info("审批建议不存在:{}", loanSubmitEnum);
        }
        return null;
    }

    /**
     * 流程异常处理
     * @param id
     * @return
     */
    @Override
    public void resumeFlow(Long id) {}

    /**
     * GPS审核提交
     * @param submitVO
     * @author yk.Li
     * @date 2020/6/29
     */
    private void submitLoan(NormalTaskSubmitVO submitVO) {
        changeCaseStatusAndSaveRecord(submitVO);
        //流程推进
        WorkFlowResponse resp = pushWorkflow(LoanSubmitEnum.SUBMIT, submitVO);
        //提交成功 保存流程记录
        afterSubmit(resp);
    }

    /**
     * @param
     * @description GPS二次补件
     * @author yk.Li
     * @date 2020/8/1
     */
    private void secondAssignment(NormalTaskSubmitVO submitVO) {
        changeCaseStatusAndSaveRecord(submitVO);
        //流程推进
        WorkFlowResponse resp = pushWorkflow(LoanSubmitEnum.SECOND_ASSIGNMENT, submitVO);
        //提交成功 保存流程记录
        afterSubmit(resp);
    }

    /**
     * GPS审核提交
     * @param submitVO
     * @author yk.Li
     * @date 2020/6/29
     */
    private void submitBackToPartners(NormalTaskSubmitVO submitVO) {
        changeCaseStatusAndSaveRecord(submitVO);
        //流程推进
        WorkFlowResponse resp = pushWorkflow(LoanSubmitEnum.BACK_PARTNERS, submitVO);
        //提交成功 保存流程记录
        afterSubmit(resp);
    }

    /**
     * @param
     * @description 提交成功修改数据
     * @author yk.Li
     * @date 2020/7/3
     */
    public void afterSubmit(WorkFlowResponse resp) {
        Assert.isTrue(Const.WORKFLOW_RESPONSE_SUCCESS == resp.getSuccess(), resp.getMessage());
    }

    /**
     * @param
     * @description 更改案件状态，保存日志
     * @author yk.Li
     * @date 2020/7/3
     */
    @Transactional(rollbackFor = Exception.class)
    public void changeCaseStatusAndSaveRecord(NormalTaskSubmitVO submitVO) {
        LoanApproveWorkflowServiceImpl service = SpringContextHolder
                .getBean(LoanApproveWorkflowServiceImpl.class);
        //删除当前任务，存入历史任务表
        service.delOldAndNewPoolHistory(submitVO);

        //保存日志
        service.saveRecord(submitVO ,CurrentPositionEnum.GPS_AUDIT);
    }

    /**
     * @param
     * @description 工作流推进
     * @author yk.Li
     * @date 2020/7/17
     */
    private WorkFlowResponse pushWorkflow(Enum<? extends AfsBaseEnum> submitButtonEnum, NormalTaskSubmitVO submitVO) {
        TaskSubmitRequest submitRequest = SpringContextHolder.getBean(LoanApproveWorkflowServiceImpl.class)
                .getTaskSubmitRequest(submitButtonEnum, submitVO);
        return workflowService.taskSubmit(submitRequest, SpringContextHolder.getBean(LoanApproveWorkflowServiceImpl.class)
                .getBusinessData(submitVO.getLoanBusinessDataVO()));
    }
}
